package com.ptbuy.base;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.util.Log;

import com.ptbuy.utils.NeverCrash;
import com.ptbuy.db.DBManager;


public class BaseApplication extends Application {
    //以下属性应用于整个应用程序，合理利用资源，减少资源浪费
    private static Context mContext;//上下文
    private static DBManager dbHelper;
    private static SQLiteDatabase db;


    private static SharedPreferences sharedPreferences;

    private static long mMainThreadId;//主线程id
    private static Handler mHandler;//主线程Handler

    @Override
    public void onCreate() {
        super.onCreate();

        mContext = getApplicationContext();

        mMainThreadId = android.os.Process.myTid();
        mHandler = new Handler();

        dbHelper = new DBManager(this);
        dbHelper.openDatabase();
        db = dbHelper.getDatabase();
        sharedPreferences = getSharedPreferences("ptbuy", MODE_PRIVATE);

        /**
         * 初始化全局异常捕获
         * 对于CPU等溢出好像没有效果
         */
        NeverCrash.init(new NeverCrash.CrashHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                Log.d("全局异常捕捉", Log.getStackTraceString(e));
            }
        });

    }
    public static SharedPreferences getSharedPreferences() {
        return sharedPreferences;
    }
    public static SQLiteDatabase getDb() {
        if (db == null) {
            dbHelper = new DBManager(mContext);
            dbHelper.openDatabase();
            db = dbHelper.getDatabase();
        }
        return db;
    }

    public static Context getContext() {
        return mContext;
    }
}
